package com.luo.controller;

import com.alibaba.fastjson.JSON;
import com.luo.model.Carts;
import com.luo.model.Result;
import com.luo.model.ResultObj;
import com.luo.service.CartService;
import com.luo.util.ListTypes;
import com.luo.util.RedisUtil;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能：
 * 作者：Luo。
 * 日期：2024/2/13 16:03
 */
@WebServlet("/member/cart")
public class FindNewCartListController extends HttpServlet {

    CartService cartService = new CartService();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String authorization = req.getHeader("authorization");
        String index = "Bearer ";
        if (authorization != null) {
            try {
                authorization = authorization.substring(authorization.lastIndexOf(index) + index.length());
                // 拿到token进行判断该token是否过期
                // 连接到Redis
                Jedis jedis = RedisUtil.getJedis();
                String fieldValue = jedis.hget(authorization, "token");
                String username = jedis.hget(authorization, "currentTime");
                String id = jedis.hget(authorization, "id");
                if (id == null) {
                    // 说明token过期了
                    ResultObj resultObj = new ResultObj();
                    resultObj.setCode("-3");
                    resultObj.setMsg("token已过期");
                    String jsonString = JSON.toJSONString(resultObj);
                    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    resp.getWriter().write(jsonString);
                    resp.getWriter().close();
                    return;
                }
                // 判断是添加购物车还是查询购物车
                String addId = req.getParameter("id");
                if (addId != null && !"".equals(addId)) {
                    // 添加购物车操作
                    ResultObj resultObj = new ResultObj();
                    String count = req.getParameter("count");
                    Map map = new HashMap();
                    map.put("count", count);
                    map.put("goodId", addId);
                    map.put("userId", id);
                    // 先查询购物车是否有该商品
                    List<Carts> carts = cartService.queryCartsById(id);
                    for (Carts c : carts) {
                        if (c.getId() == Integer.parseInt(addId)){
                            // 如果有则更新其count
                            int i = cartService.updateOneCartById(map);
                            if (i > 0) {
                                resultObj.setCode("1");
                                resultObj.setMsg("添加成功");
                            } else {
                                resultObj.setCode("-1");
                                resultObj.setMsg("添加失败");
                            }
                            String jsonString = JSON.toJSONString(resultObj);
                            resp.getWriter().write(jsonString);
                            resp.getWriter().close();
                            return;
                        }
                    }
                    // 如果没有
                    int i = cartService.addOneCart(map);
                    if (i > 0) {
                        resultObj.setCode("1");
                        resultObj.setMsg("添加成功");
                    } else {
                        resultObj.setCode("-1");
                        resultObj.setMsg("添加失败");
                    }
                    String jsonString = JSON.toJSONString(resultObj);
                    resp.getWriter().write(jsonString);
                    resp.getWriter().close();
                    return;
                } else {
                    // 根据id进行数据库的查询
                    List<Carts> carts = cartService.queryCartsById(id);
                    List<Object> objList = ListTypes.getObjList(carts);
                    Result result = new Result();
                    result.setCode("1");
                    result.setMsg("查询成功");
                    result.setResult(objList);
                    String jsonString = JSON.toJSONString(result);
                    resp.getWriter().write(jsonString);
                    resp.getWriter().close();
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("出现了异常token");
            }
        }
    }
}
